<?php
/**
 * Created by PhpStorm.
 *
 * Date: 2018/11/17
 * Time: 上午10:00
 */

namespace app\common\model;


use think\Exception;

class Goods extends Common
{
    protected function base($query)
    {
        $query->where("isshow", 1);
    }

    /**
     * 获取在售商品列表
     */
    public static function getGoodsList()
    {
        return self::order("sort desc")->select();
    }

    /**
     * 校验商品信息
     */
    public static function checkGoods($good_id, $user_id)
    {
        $good = self::get(["id"=>$good_id]);
        if(empty($good)){
            throw new Exception("商品已下架");
        }
        //商品是否可销售
        if($good["isclose"] == 2){
            $closestr = empty($good["closestr"])?config("setting.site_pro_info"):$good["closestr"];
            throw new Exception($closestr);
        }
        //平台是否可购买
        if(config("setting.site_pro_all") == 2){
            $closestr = config("setting.site_pro_info");
            throw new Exception($closestr);
        }
        $now_date = strtotime(date("Ymd"));
        //当前商品销售时间已经超过当前时间
        if($good["time_end"]+$now_date<time()){
            throw new Exception("当前商品今日已售完，明天再来吧");
        }
        if(time()<$good["time_start"]+$now_date){
            //当前商品可预约，查询是否已经预约过
            $r = db("apply")->where("proid", $good_id)->where("uid", $user_id)->where("nowdate", date("Ymd"))->find();
            if($r){
                throw new Exception("你已经预约过该商品,刷新后重试");
            }
        }
        //校验今天是否已经购买过此商品
        $order = db(config("db_order_table"))->where("buyuid='".$user_id."' and productid='".$good_id."' and thatdatetime='".$now_date."'")->find();
        if(!empty($order)){
            throw new Exception("此商品每天只能购买一次！");
        }

        return $good;
    }

}
